(() => {
  function initLightbox() {
    const lb = document.getElementById('lightbox');
    if (!lb) return;
    const img = lb.querySelector('img');
    const closeBtn = lb.querySelector('.lb-close');

    function open(src, alt) {
      if (!src) return;
      img.src = src;
      img.alt = alt || '';
      lb.classList.add('open');
      document.body.style.overflow = 'hidden';
    }
    function close() {
      lb.classList.remove('open');
      document.body.style.overflow = '';
      img.src = '';
      img.alt = '';
    }

    lb.addEventListener('click', (e) => {
      if (e.target === lb) close();
    });
    if (closeBtn) closeBtn.addEventListener('click', close);
    window.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') close();
    });

    document.addEventListener('click', (e) => {
      const t = e.target;
      if (t && t.tagName === 'IMG' && t.closest('.card')) {
        e.preventDefault();
        open(t.getAttribute('src'), t.getAttribute('alt'));
      }
    });
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initLightbox);
  } else {
    initLightbox();
  }
})();

